<?php

class User_votes extends CI_Model{
    function __construct(){
        parent::__construct();
    }
    
    function getNumVotes($mealtime_id, $meal_id){
        $this->db->from("user_votes as UV");
        $this->db->join("mealtime_meals as MTM", "MTM.mealtime_meals_id = UV.mealtime_meals_id");
        $this->db->where("MTM.mealtime_id",  $mealtime_id);
        $this->db->where("MTM.meal_id", $meal_id);
        
        return $this->db->get()->num_rows();
    }
    
    function vote($user_id, $tonightsMeals, $mealtime_meal_id) {
        
        $tm_meal_id = array();
        
        foreach ($tonightsMeals->result() as $meal) {
            $tm_meal_id[] = $meal->mealtime_meals_id;
        }
        
        $this->db->where_in('mealtime_meals_id', $tm_meal_id);
        $this->db->where('user_id', $user_id);
        
        $result = $this->db->get('user_votes');
        
        if ($result->num_rows() == 0) {
            return $this->insertVote($user_id, $mealtime_meal_id);
        }
        else {
            return $this->updateVote($user_id, $mealtime_meal_id, $result->row()->mealtime_meals_id);
        }        
    }
    
    private function insertVote($user_id, $mealtime_meal_id) {
        $data = array(
            'mealtime_meals_id' => $mealtime_meal_id,
            'user_id' => $user_id
        );
        
        $this->db->trans_start();
        $this->db->insert('user_votes', $data);
        $this->db->trans_complete();
        return $this->db->trans_status();
    }
    
    private function updateVote($user_id, $mealtime_meal_id, $oldVote) {
        $data = array(
            'mealtime_meals_id' => $mealtime_meal_id
        );
        
        $this->db->trans_start();
        
        $this->db->where('user_id', $user_id);
        $this->db->where('mealtime_meals_id', $oldVote);
        
        $this->db->update('user_votes', $data);
        
        $this->db->trans_complete();
        return $this->db->trans_status();
    }
    
    function deleteVote($user_id, $mealtime_id){
        
        $this->db->from('mealtime_meals as MTM');
        $this->db->join('user_votes as UV', 'UV.mealtime_meals_id = MTM.mealtime_meals_id');
        
        $this->db->where('mealtime_id', $mealtime_id);
        $this->db->where('user_id', $user_id);
        $this->db->select('user_votes_id');
        $user_votes = $this->db->get();
        
        if ($user_votes->num_rows() == 0){
            return false;
        }
                
        $this->db->where('user_votes_id', $user_votes->row()->user_votes_id);
        $this->db->delete('user_votes');
        
        return true;
    }
}

